package models

import "github.com/jinzhu/gorm"

type Mentor struct {
	Model
	Name string `json:"name"`
	Email string `json:"email"`
	Phone string `json:"phone"`
	Zoom string `json:"zoom"`
	WhatsApp string `json:"whats_app"`
	WeChat string `json:"we_chat"`
	UserId int
}

// ExistMentorByID checks if an Mentor exists based on ID
func ExistMentorByID(id int) (bool, error){
	var mentor Mentor
	err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&mentor).Error
	if err != nil && err != gorm.ErrRecordNotFound{
		return false, err
	}

	if mentor.ID > 0 {
		return true, nil
	}

	return false, nil
}

// GetMentorTotal gets the total number of mentor based on the constraints
func GetArticleTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&Mentor{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

// GetMentors gets a list of mentors based on paging constraints
func GetMentors(pageNum int, pageSize int, maps interface{}) ([]*Mentor, error) {
	var mentors []*Mentor
	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&mentors).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return mentors, nil
}

// GetMentor Get a single mentor based on ID
func GetMentor(id int) (*Mentor, error) {
	var mentor Mentor
	err := db.Where("id = ? AND deleted_on = ? ", id, 0).First(&mentor).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &mentor, nil
}

// EditMentor modify a single mentor
func EditMentor(id int, data interface{}) error {
	if err := db.Model(&Mentor{}).Where("id = ? AND deleted_on = ? ", id, 0).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

// AddMentor add a single mentor
func AddMentor(data map[string]interface{}) error {
	mentor := Mentor{
		Name: data["name"].(string),
		Email: data["email"].(string),
		Phone: data["phone"].(string),
		Zoom: data["zoom"].(string),
		WeChat: data["we_chat"].(string),
		WhatsApp: data["whats_app"].(string),
		UserId: data["user_id"].(int),
	}
	if err := db.Create(&mentor).Error; err != nil {
		return err
	}

	return nil
}

// DeleteMentor delete a single mentor
func DeleteMentor(id int) error {
	if err := db.Where("id = ?", id).Delete(Mentor{}).Error; err != nil {
		return err
	}

	return nil
}

// CleanAllMentor clear all mentor
func CleanAllMentor() error {
	if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Mentor{}).Error; err != nil {
		return err
	}

	return nil
}